import os.path
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains

class MouseOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://sahitest.com/demo/clicks.htm")

    # 单击
    # 方法1
    def click(self):
        time.sleep(3)
        btn = self.driver.find_element(By.XPATH, "//form/input[3]")
        btn.click()

    # 方法2
        ac = ActionChains(self.driver)
        ac.click(btn).perform()

    # 右击
    def context_click(self):
        time.sleep(3)
        ac = ActionChains(self.driver)
        btn = self.driver.find_element(By.XPATH, "/html/body/form/input[4]")
        ac.context_click(btn).perform()

    # 双击
    def double_click(self):
        time.sleep(2)
        ac = ActionChains(self.driver)
        btn = self.driver.find_element(By.CSS_SELECTOR, 'input[value="dbl click me"]')
        ac.double_click(btn).perform()

    # 拖动
    def drag_and_drop(self):
        self.driver.get("https://sahitest.com/demo/dragDropMooTools.htm")
        time.sleep(2)
        ac = ActionChains(self.driver)
        source = self.driver.find_element(By.ID, "dragger")
        target = self.driver.find_element(By.XPATH, "//div[4]")
        ac.drag_and_drop(source, target).perform()

    # 悬停
    def move_element(self):
        self.driver.get("https://sahitest.com/demo/mouseover.htm")
        time.sleep(2)
        ac = ActionChains(self.driver)
        btn = self.driver.find_element(By.XPATH, "//div/div")
        ac.move_to_element(btn).perform()

    # 长按点击
    def click_hold(self):
        file = "file:///" + os.path.abspath("html") + "/mouse_hold.html"
        self.driver.get(file)
        btn = self.driver.find_element(By.ID, "btn1")
        ac = ActionChains(self.driver)
        ac.click_and_hold(btn).perform()

    def quit(self):
        time.sleep(30)
        self.driver.quit()

if __name__ == '__main__':
    mo = MouseOperation()
    # mo.click()
    # mo.context_click()
    # mo.double_click()
    # mo.drag_and_drop()
    # mo.move_element()
    mo.click_hold()
    mo.quit()

